package com.yfqy.app.modules.product.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import com.yfqy.app.domain.mapper.CategoryMapper;
import com.yfqy.app.modules.product.service.CategoryService;
import com.yfqy.app.modules.product.vo.CategoryVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public List<CategoryVO> all() {
        List<CategoryVO> categories = categoryMapper.selectAllRoot();
        if (CollUtil.isNotEmpty(categories)) {
            List<Long> ids = categories.stream().map(CategoryVO::getId).toList();
            List<CategoryVO> children = categoryMapper.selectByParentIds(ids);
            if (CollUtil.isNotEmpty(children)) {
                Map<Long, List<CategoryVO>> groupByParentId = children.stream().collect(Collectors.groupingBy(CategoryVO::getParentId));
                categories.forEach(dto -> dto.setChildren(groupByParentId.get(dto.getId())));
            }
        }
        return Collections.emptyList();
    }

}
